import subprocess
import sys
from time import sleep

row, thread, repeat = '2000000', '5', '4'
server_list = (
    ('mysql8', 'MySQL80'),
    ('sqlserver', 'MSSQLSERVER'),
    ('mysql', 'MySQL57'),
    ('postgre', 'postgresql-x64-10'),
    ('sql2017', 'MSSQL$MSSQL2017,SQLBrowser'),
    ('maria', 'MariaDB'),
    ('oracle', 'OracleOraDB12Home1TNSListener,OracleServiceORCL'),
    ('h2', 'H2DatabaseService'),
    ('db2', 'DB2-0,DB2DAS00'),
    ('derby', 'derby'),
    ('firebird', 'FirebirdServerDefaultInstance'),
    ('hsql', 'hsql')
)
keep_alive = 'mysql'
java_cmd = '''"C:\\Program Files\\Java\\jdk-11.0.1\\bin\\java.exe"  -Dfile.encoding=UTF-8 -classpath D:\\dbbmlite\\out\\production\\dbbmlite;D:\\dbeaver-drivers\\maven\\maven-central\\org.xerial\\sqlite-jdbc-3.23.1.jar;D:\\dbeaver-drivers\\maven\\maven-central\\mysql\\mysql-connector-java-5.1.44.jar;D:\\dbbmlite\\lib\\kotlin-stdlib.jar;D:\\dbbmlite\\lib\\kotlin-reflect.jar;D:\\dbbmlite\\lib\\kotlin-test.jar;D:\\dbbmlite\\lib\\kotlin-stdlib-jdk7.jar;D:\\dbbmlite\\lib\\kotlin-stdlib-jdk8.jar;D:\\dbbmlite\\resources\\jdbc\\connector-api-1.5.jar;D:\\dbbmlite\\resources\\jdbc\\antlr-runtime-4.7.jar com.deepinjava.dbbmlite.Application'''


def exec(cmd, code):
    print(cmd)
    ret = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)  # print(ret)
    while True:
        line = ret.stdout.readline().decode(code)
        print(line)
        if not line:
            break


def start_server(server_name: str):
    print(server_name)
    for s in server_name.split(','):
        exec("net start %s" % s, 'GBK')


def stop_server(server_name: str):
    for s in server_name.split(','):
        exec("net stop %s" % s, 'GBK')


def run_bench(prof: str):
    exec('%s %s %s %s %s' % (java_cmd, row, thread, prof, repeat), 'UTF8')


if __name__ == '__main__':
    print('准备运行DBikini性能测试脚本！')

    run_list = sys.argv[1] if len(sys.argv) == 2 else None

    for serv in server_list:
        if run_list is not None and not (serv[0] in run_list):
            continue
        print('启动服务： %s' % serv[0])
        start_server(serv[1])
        print('运行Bench： %s' % serv[0])
        run_bench(serv[0])
        if serv[0] != keep_alive:
            print('停止服务： %s' % serv[0])
            stop_server(serv[1])
        else:
            print('跳过守护进程： %s' % serv[0])

